package server.communication;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class RootThread extends Thread{

	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	private MessageProcessor mesProc;
	
	public PrintWriter getOutStream()
	{
		return out;
	}
	public BufferedReader getInStream()
	{
		return in;
	}
	
	public Socket getSocket()
	{
		return socket;
	}
	
	public RootThread(Socket socket)
	{
		this.socket = socket;
		mesProc = new MessageProcessor(null);
		try
		{
			socket.setSoTimeout(60000*30);
			socket.setKeepAlive(true);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream(), true);
		}
		catch(Exception e)
		{
			System.err.println("Unable to initialize RootThread");
		}
	}
	
	@Override
	public void run()
	{
		String input=null,answer;
		try
		{
			while ((input = in.readLine()) != null)
			{
				System.out.println("RootInput: " + input);
				answer = mesProc.process(input);
				if (answer != null)
				{
					System.out.println("RootOutput: " + answer);
					out.println(answer);
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Root disconnected");
		}
	}
	
	public void closeConnection()
	{
		try
		{
			socket.close();
		}
		catch(Exception e)
		{
			System.err.println("Unable to close connection for RootThread");
		}
	}
}
